import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:ost_flutter_module/class/entity/store/store_map_entity.dart';
import 'package:ost_flutter_module/class/store/city_page/bloc/city_page_bloc.dart';
import 'package:ost_flutter_module/class/store/city_page/store_city_page.dart';
import 'package:ost_flutter_module/class/store/course_page/bloc/course_page_bloc.dart';
import 'package:ost_flutter_module/class/store/course_page/widgets/store_course_drop_item.dart';
import 'package:ost_flutter_module/class/store/course_page/widgets/store_course_menu.dart';
import 'package:ost_flutter_module/common/adapt.dart';
import 'package:ost_flutter_module/common/color.dart';
import 'package:ost_flutter_module/common/defines_macro.dart';
import 'package:ost_flutter_module/common/utils.dart';
import 'package:ost_flutter_module/help/ost_route.dart';
import 'package:ost_flutter_module/main.dart';
import 'package:ost_flutter_module/widget/custom_widget/custome_underlineIndicator.dart';
import 'package:ost_flutter_module/widget/custom_widget/image_text_button.dart';
import 'package:ost_flutter_module/widget/custom_widget/swiper.dart';
import 'package:ost_flutter_module/widget/drop_down_widget/drop_down_widget.dart';
import 'package:ost_flutter_module/widget/loading/loading_empty_widget.dart';
import 'package:ost_flutter_module/widget/loading/loading_error_widget.dart';
import 'package:ost_flutter_module/widget/loading/loading_view.dart';
import 'package:ost_flutter_module/widget/loading/loading_widget.dart';

import 'store_course_home_list_page.dart';

class StoreCourseHomePage extends StatelessWidget {
  const StoreCourseHomePage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocProvider<CoursePageBloc>(
      create: (context) => CoursePageBloc()
        ..add(CoursePageFetchDataInitial(
          banner: CoursePageBanner(StoreDefineCode.store_course_code),
          course: CoursePageFetchData(
            city: '上海市',
            code: StoreDefineCode.store_course_assessment,
            action: null
          ),
        )),
      child: _StoreCourseLoadingWidget(),
    );
  }
}

class _StoreCourseLoadingWidget extends StatelessWidget {
  const _StoreCourseLoadingWidget({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CoursePageBloc, CoursePageState>(
      builder: (context, state) {
        var _dataModel = context.read<CoursePageBloc>().dataModel;

        return LoadingView(
          status: _dataModel?.loadingStatus,
          loadingContent: LoadingWidget(),
          errorContent: LoadingErrorWidget(
              errorTitle: _dataModel?.errorMsg, onRetry: () {}),
          successContent: StoreCourseHomeTabController(),
          emptyContent: LoadingEmptyWidget(),
        );
      },
    );
  }
}

class StoreCourseHomeTabController extends StatefulWidget {
  StoreCourseHomeTabController({Key key}) : super(key: key);

  @override
  _StoreCourseHomeTabControllerState createState() =>
      _StoreCourseHomeTabControllerState();
}

class _StoreCourseHomeTabControllerState
    extends State<StoreCourseHomeTabController>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin {
  double menuHeight = Adapt.px(44) * 6;

  TabController controller;

  List<String> _lists = ['服务咨询', '我的课程', '上课指引'];
  List<String> _tabLists = ['为你推荐', '专家评估', '名师讲座', '家长培训'];

  List<String> _dropDownHeaders = ['中心选择', '适应症', '授课形式', '课程班型'];
  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();

  GlobalKey _stackKey = GlobalKey();
  GlobalKey globalKey;
  ScrollController scrollController;

  @override
  void initState() {
    super.initState();
    controller = TabController(vsync: this, length: 4);
    scrollController = ScrollController();
    globalKey = GlobalKey();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  // 0 线下， 1 线上
  List<StoreMapEntity> _shiftOnlineList = [];
  _handOnlineList() {
    _shiftOnlineList.add(StoreMapEntity(value: '线下', id: '0'));
    _shiftOnlineList.add(StoreMapEntity(value: '线上', id: '1'));
  }

// 课程班型
  List<StoreMapEntity> _shiftTypeList = [];
  // 适应症
  List<StoreMapEntity> _shiftStatusList = [];
  _handleMapList(List<StoreMapEntity> list) {
    for (var item in list) {
      if (item.key == StoreDefineCode.store_course_shift_type) {
        _shiftTypeList.add(item);
      } else if (item.key == StoreDefineCode.store_course_shift_Status) {
        _shiftStatusList.add(item);
      }
    }
  }

  @override
  bool get wantKeepAlive => true;

  void _onTapHead(BuildContext context, int index) {
    RenderObject renderObject = globalKey.currentContext.findRenderObject();

    scrollController
        .animateTo(scrollController.offset + renderObject.semanticBounds.height,
            duration: Duration(milliseconds: 150), curve: Curves.ease)
        .whenComplete(() {
      _dropdownMenuController.dropDownMenuTop =
          renderObject.semanticBounds.height + Adapt.px(92);
    });
  }

  GZXDropDownHeader _buildHeader(BuildContext context) {
    return GZXDropDownHeader(
        stackKey: _stackKey,
        controller: _dropdownMenuController,
        height: Adapt.px(44),
        borderColor: Colors.transparent,
        dividerColor: Colors.transparent,
        style: TextStyle(color: Color(0xFF666666), fontSize: 14),
        dropDownStyle:
            TextStyle(fontSize: 14, color: Theme.of(context).primaryColor),
        items: _dropDownHeaders.map((e) => GZXDropDownHeaderItem(e)).toList(),
        onItemTap: (index) {
          _onTapHead(context, index);
        });
  }

  GZXDropDownMenu _buildMenu() {
    return GZXDropDownMenu(
      controller: _dropdownMenuController,
      animationMilliseconds: 300,
      menus: [
        GZXDropdownMenuBuilder(
            dropDownHeight: menuHeight,
            dropDownWidget: StoreCourseMenu(onTap: (selectValue) {
              _dropDownHeaders[0] = selectValue;
              _dropdownMenuController.hide();
              setState(() {});
            })),
        GZXDropdownMenuBuilder(
            dropDownHeight: menuHeight,
            dropDownWidget: StoreCourseMenu(onTap: (selectValue) {
              _dropDownHeaders[1] = selectValue;
              _dropdownMenuController.hide();
              setState(() {});
            })),
        GZXDropdownMenuBuilder(
            dropDownHeight: menuHeight,
            dropDownWidget: StoreCourseMenuGrid(onTap: (selectValue) {
              _dropDownHeaders[1] = selectValue;
              _dropdownMenuController.hide();
              setState(() {});
            })),
        GZXDropdownMenuBuilder(
            dropDownHeight: menuHeight,
            dropDownWidget: StoreCourseMenuGrid(onTap: (selectValue) {
              _dropDownHeaders[1] = selectValue;
              _dropdownMenuController.hide();
              setState(() {});
            })),
      ],
    );
  }

  @override
  // ignore: must_call_super
  Widget build(BuildContext context) {
    return BlocBuilder<CoursePageBloc, CoursePageState>(
      builder: (context, state) {
        var bannerList = context.read<CoursePageBloc>().banner.dataList;
        var mapList = context.read<CoursePageBloc>().map.dataList;
        var dataList = context.read<CoursePageBloc>().dataModel.dataList;

        return Stack(
          key: _stackKey,
          children: [
            CustomScrollView(
              controller: scrollController,
              slivers: [
                SliverList(
                  key: globalKey,
                  delegate: SliverChildListDelegate([
                    Padding(
                      padding: EdgeInsets.only(top: Adapt.px(10)),
                      child: Column(
                        children: [
                          bannerList.isNotEmpty
                              ? SwiperWidget(swiperList: bannerList)
                              : Container(),
                          CourseButtonBar(lists: _lists),
                        ],
                      ),
                    )
                  ]),
                ),
                SliverPersistentHeader(
                  pinned: true,
                  delegate: _SliverAppBarDelegate(builder: (context) {
                    return Container(
                      color: Colors.white,
                      child: Column(
                        children: [
                          GTabbar(
                              controller: controller,
                              list: _tabLists,
                              color: colorFAFAFA),
                          _buildHeader(context),
                        ],
                      ),
                    );
                  }),
                ),
                SliverList(
                    delegate: SliverChildBuilderDelegate((context, index) {
                  return StoreCourseHomeListPage(type: 1);
                }, childCount: 1)),
                // SliverFillRemaining(
                //   fillOverscroll: true,
                //   child: TabBarView(
                //     controller: controller,
                //     children: _tabLists.map((e) {
                //       return StoreCourseHomeListPage(type: 1);
                //       // return Builder(
                //       //   builder: (context) {
                //       //     return CustomScrollView(
                //       //       shrinkWrap: true,
                //       //       physics: NeverScrollableScrollPhysics(),
                //       //       slivers: [
                //       //         // SliverOverlapInjector(
                //       //         //     handle: NestedScrollView
                //       //         //         .sliverOverlapAbsorberHandleFor(
                //       //         //             context)),
                //       //         SliverToBoxAdapter(
                //       //             child: StoreCourseHomeListPage(
                //       //                 type: _tabLists.indexOf(e))),
                //       //       ],
                //       //     );
                //       //   },
                //       // );
                //     }).toList(),
                //   ),
                // ),
              ],
            ),
            _buildMenu(),
          ],
        );
      },
    );
  }

//   @override
//   Widget build(BuildContext context) {
//     return Stack(key: _stackKey, children: [
//       NestedScrollView(
//           headerSliverBuilder: (context, innerBoxIsScrolled) {
//             return [
//               SliverOverlapAbsorber(
//                 handle:
//                     NestedScrollView.sliverOverlapAbsorberHandleFor(context),
//                 sliver: SliverAppBar(
//                   backgroundColor: colorFAFAFA,
//                   forceElevated: innerBoxIsScrolled,
//                   flexibleSpace: Column(
//                     children: [
//                       SizedBox(
//                         height: Adapt.px(10),
//                       ),
//                       SwiperWidget(
//                           swiperList: [SwiperModel(url: default_image)]),
//                       CourseButtonBar(lists: _lists),
//                     ],
//                   ),
//                   bottom: PreferredSize(
//                       child: Container(),
//                       preferredSize: Size.fromHeight(Adapt.px(210))),
//                 ),
//               ),

//               ///停留在顶部的TabBar
//               SliverPersistentHeader(
//                 pinned: true,
//                 delegate: _SliverAppBarDelegate(builder: (context) {
//                   return Column(
//                     children: [
//                       GTabbar(
//                           controller: _controller,
//                           list: _tabLists,
//                           color: colorFAFAFA),
//                       GZXDropDownHeader(
//                           items: _dropDownHeaders
//                               .map((e) => GZXDropDownHeaderItem(e))
//                               .toList(),
//                           stackKey: _stackKey,
//                           controller: _dropdownMenuController,
//                           height: Adapt.px(44),
//                           borderColor: Colors.transparent,
//                           dividerColor: Colors.transparent,
//                           style:
//                               TextStyle(color: Color(0xFF666666), fontSize: 14),
//                           dropDownStyle: TextStyle(
//                             fontSize: 14,
//                             color: Theme.of(context).primaryColor,
//                           )),
//                     ],
//                   );
//                 }),
//               ),
//               SliverFillRemaining(
//                 fillOverscroll: true,
//                 child: TabBarView(
//                   controller: _controller,
//                   children: _tabLists.map((e) {
//                     return Builder(
//                       builder: (context) {
//                         return
//                             // CustomScrollView(
//                             //   slivers: [
//                             //     SliverOverlapInjector(
//                             //         handle: NestedScrollView
//                             //             .sliverOverlapAbsorberHandleFor(context)),
//                             //     SliverToBoxAdapter(
//                             //         child:
//                             StoreCourseHomeListPage(
//                           type: _tabLists.indexOf(e),
//                           // )
//                           //           ),
//                           // ],
//                         );
//                       },
//                     );
//                   }).toList(),
//                 ),
//               ),
//             ];
//           },
//           body: Container()
//           // TabBarView(
//           //   controller: _controller,
//           //   children: _tabLists.map((e) {
//           //     return SafeArea(
//           //       top: false,
//           //       bottom: false,
//           //       child: Builder(
//           //         builder: (context) {
//           //           return CustomScrollView(
//           //             slivers: [
//           //               SliverOverlapInjector(
//           //                   handle: NestedScrollView.sliverOverlapAbsorberHandleFor(
//           //                       context)),
//           //               SliverToBoxAdapter(
//           //                   child: StoreCourseHomeListPage(
//           //                       type: _tabLists.indexOf(e))),
//           //             ],
//           //           );
//           //         },
//           //       ),
//           //     );
//           //   }).toList(),
//           // ),
//           ),
//       GZXDropDownMenu(
//         controller: _dropdownMenuController,
//         animationMilliseconds: 300,
//         menus: [
//           GZXDropdownMenuBuilder(
//               dropDownHeight: 40 * 8.0,
//               dropDownWidget: _buildAddressWidget((selectValue) {
//                 _dropDownHeaders[0] = selectValue;
//                 _dropdownMenuController.hide();
//                 setState(() {});
//               })),
//           GZXDropdownMenuBuilder(
//               dropDownHeight: 40 * 8.0,
//               dropDownWidget:
//                   _buildConditionListWidget(_brandSortConditions, (value) {
//                 _selectBrandSortCondition = value;
//                 _dropDownHeaders[1] = _selectBrandSortCondition.name;
//                 _dropdownMenuController.hide();
//                 setState(() {});
//               })),
//           GZXDropdownMenuBuilder(
//               dropDownHeight: 40.0 * _distanceSortConditions.length,
//               dropDownWidget: Container()),
//           GZXDropdownMenuBuilder(
//               dropDownHeight: 40.0 * _distanceSortConditions.length,
//               dropDownWidget: Container()),
//         ],
//       ),
//     ]);
//   }
}

///TabBar的代理
class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  static const double height = 92;

  WidgetBuilder builder;
  _SliverAppBarDelegate({this.builder}) : assert(builder != null);

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return builder(context);
  }

  @override
  double get maxExtent => Adapt.px(height);

  @override
  double get minExtent => Adapt.px(height);

  @override
  bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}

class GTabbar extends StatelessWidget {
  final TabController controller;
  final List list;
  final Color color;

  const GTabbar({Key key, this.controller, this.list, this.color})
      : super(key: key);
  @override
  Widget build(BuildContext context) {
    return PreferredSize(
      preferredSize: Size.fromHeight(Adapt.px(48)),
      child: Container(
        color: color ?? Colors.white,
        child: TabBar(
          controller: controller,
          indicator: GUnderlineTabIndicator(
            width: 30,
            borderSide: BorderSide(width: 4.0, color: colorFACD33),
          ),
          labelColor: color42270C,
          unselectedLabelColor: color999999,
          labelStyle: TextStyle(fontSize: 16),
          tabs: list.map((e) => Tab(text: e)).toList(),
        ),
      ),
    );
  }
}

class CourseButtonBar extends StatelessWidget {
  final List lists;
  static const _svgs = ['service_consule', 'my_course', 'course_guide'];

  const CourseButtonBar({Key key, this.lists}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return GridView.count(
      padding: EdgeInsets.only(
          top: Adapt.px(10), left: Adapt.px(10), right: Adapt.px(10)),
      crossAxisCount: 3,
      crossAxisSpacing: Adapt.px(10),
      childAspectRatio: 3.14,
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      children: lists
          .map((e) => GImageTextButton(
                e,
                svg: Utils.svgAssets(_svgs[lists.indexOf(e)]),
                onTap: (_) {
                  var index = lists.indexOf(e);
                  if (index == 0)
                    Navigator.pushNamed(
                        context, GRouter.course_service_consult_page);
                  else if (index == 2)
                    Navigator.pushNamed(context, GRouter.course_guide_page);
                },
              ))
          .toList(),
    );
  }
}
